<?php

/**
 * 文章模型
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-16
 */

namespace app\common\model;

use fw\db\DB;
use fw\tool\Request;

class Art
{
    /**
     * 获取一条数据
     *
     * @param array $args
     *
     * @return array
     */
    public function getInfo($args)
    {
        // 参数获取
        $art_id = (int)Request::input($args, 'art_id');
        $alias = Request::input($args, 'alias', 'trim');

        $art = [];
        if ($art_id > 0) {
            $art = DB::table('art')
                ->where('art_id=:art_id', [':art_id' => $art_id])
                ->selectRow();
        } elseif (!empty($alias)) {
            $art = DB::table('art')
                ->where('alias=:alias', [':alias' => $alias])
                ->selectRow();
        }

        return $art;
    }

    /**
     * 获取列表或统计条数
     *
     * @param array $args
     *
     * @return array|int
     */
    public function getList($args)
    {
        // 参数获取
        $art_ids = Request::input($args, 'art_ids', 'trim');

        $is_hide = Request::input($args, 'is_hide', function ($pa) {
            return in_array($pa, [0, 1]) ? $pa : 0;
        });

        $types = Request::input($args, 'types', 'trim');
        $page = Request::input($args, 'page', 'intval', 1);
        $length = Request::input($args, 'length', 'intval', 100);

        $sort_way = Request::input($args, 'sort_way', 'trim', 'DESC');
        $sort_way = strtoupper($sort_way);

        $is_count = Request::input($args, 'is_count', 'boolval', false);

        // 条件组装
        $prep = $map = [];
        if (!empty($art_ids)) {
            $map[] = 'art_id IN (' . $art_ids . ')';
        }
        if (!is_null($is_hide)) {
            $map[] = 'is_hide=:is_hide';
            $prep[':is_hide'] = $is_hide;
        }
        if (!empty($types)) {
            $map[] = 'types=:types';
            $prep[':types'] = $types;
        }
        $where = implode(' AND ', $map);

        // 查询条数
        if ($is_count === true) {
            return DB::table('art')->where($where, $prep)->count();
        }

        // 查询列表
        $rows = DB::table('art')
            ->where($where, $prep)
            ->order('art_id ' . $sort_way)
            ->limit(($page - 1) * $length . ',' . $length)
            ->select();

        return $rows;
    }
}
